package com.sys.utils;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @ClassName: RequestEncodingUtils 
 * @Description: TODO(解决request乱码的工具类)
 * @author 詹金浩 
 * @date 2018年3月11日 下午2:27:04
 */
public class RequestEncodingUtils extends HttpServletRequestWrapper {
	private HttpServletRequest request;
	private Boolean isEncoded = false;
	
	public RequestEncodingUtils(HttpServletRequest request) {
		super(request);
		this.request = request;
	}
	@Override
	public Map<String, String[]> getParameterMap() {
		
		String method = request.getMethod();
		
		Map<String, String[]> parameterMap = request.getParameterMap();
		//处理Post请求
		if(method.equalsIgnoreCase("post")) {
			try {
				request.setCharacterEncoding("utf-8");
				parameterMap =  request.getParameterMap();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}else if (method.equalsIgnoreCase("get")) {  //处理Get请求
			//保证编码只被执行一次
			if(!isEncoded) {
				for(String key : parameterMap.keySet()) {
					String []values = parameterMap.get(key);
					if(values != null) {
						for(int i = 0; i < values.length; i++) {
							try {
								values[i] = new String(values[i].getBytes("ISO-8859-1"),"utf-8");
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
			isEncoded = true;
		}
		return parameterMap;
	}
	
	@Override
	public String[] getParameterValues(String name) {
		Map<String, String[]> parameterMap = this.getParameterMap();
		String []values = parameterMap.get(name);
		return values;
	}
	
	@Override
	public String getParameter(String name) {
		String []values = getParameterValues(name);
		return values!=null?values[0]:null;
	}
}